#!/bin/bash
# CopyRight (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.

function main()
{
  local cur_dir=$(cd $(dirname ${0});pwd)
  local parent_dir=$(dirname ${cur_dir})
  if [[ -n $(readlink "${parent_dir}"/deploy/control_resource.sh) ]] ; then
    echo "The control_resource.sh has soft link risks"
    exit 1
  fi
  if [[ -n $(readlink "${cur_dir}"/launcher.py) ]] ; then
    echo "The launcher.py has soft link risks"
    exit 1
  fi

  local option=${1}
  case ${option} in
    "start")
      python3 "${cur_dir}"/launcher.py $@
      sleep 10s
      pid_file="${parent_dir}/var/run/launcher.pid"
      # check pid file exists
      if [ -f "$pid_file" ]; then
          pid=$(cat "$pid_file")
          if ps -p "$pid" > /dev/null 2>&1; then
            sh "${parent_dir}"/deploy/control_resource.sh
            sh "${parent_dir}"/deploy/log.sh "Start LoadsMetric"
          else
              # if process doesn't exist, then empty pid file and return 1
              sh "${parent_dir}"/deploy/log.sh "Process $pid is not running. Returning error and cleaning up pid file."
              sh "${parent_dir}"/deploy/log.sh "Please check the service running logs."
              > "$pid_file"
              exit 1
          fi
      else
          sh "${parent_dir}"/deploy/log.sh "No pid file found. Returning error."
          exit 1
      fi
      ;;
    "stop")
      python3 "${cur_dir}"/launcher.py $@
      sh "${parent_dir}"/deploy/log.sh "Stop LoadsMetric"
      ;;
    "kill")
      python3 "${cur_dir}"/launcher.py $@
      sh "${parent_dir}"/deploy/log.sh "Kill LoadsMetric"
      ;;
    "restart")
      python3 "${cur_dir}"/launcher.py $@
      sh "${parent_dir}"/deploy/control_resource.sh
      sh "${parent_dir}"/deploy/log.sh "Restart LoadsMetric"
      ;;
    "status")
      python3 "${cur_dir}"/launcher.py $@
      ;;
    *)
      echo "USAGE: ${0}  start, stop, kill, restart, status"
      exit 1
  esac
}

main $@